package com.aglhz.nature.view;

import java.io.File;
import java.util.LinkedList;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;
import com.aglhz.base.BaseActivity;
import com.aglhz.nature.R;
import com.aglhz.nature.utils.Constants;
import com.aglhz.nature.utils.MD5;
import com.tencent.mm.sdk.modelpay.PayReq;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.JavascriptInterface;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.webkit.WebChromeClient.FileChooserParams;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

public class ArrowDetailsWebActivity extends BaseActivity{
	
	private String mCameraFilePath = null;  
	private ValueCallback<Uri> mUploadMessage;
	public ValueCallback<Uri[]> uploadMessage;
	public static final int REQUEST_SELECT_FILE = 100;
	private final static int FILECHOOSER_RESULTCODE = 1;
	private ArrowDetailsWebActivity arrowDetailsWebActivity ;
	
	private WebView arrowWebView;
	private String all_order_url;
	private String pay_arrow_url;
	private String accept_arrow_url ;
	private String arrow_evaluate_url;
	private String back_arrow_url;
	private String repair_url;
	private String 	url;
	private String address_management_url;
	private String showcenter_url;
	private String myshow_url;
	private SharedPreferences sharedPreferences;  
	private String token;
	private String wx_token;
	private String nor_token;
	/*private ImageButton back;
	private TextView title;*/
	private IWXAPI api;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.arrowdetailsweb);
		setActionBarTitle("订单");
		api = WXAPIFactory.createWXAPI(getApplication(), Constants.WX_KEY);
		//获取sharedPreferences里面的信息,微信
		sharedPreferences =getSharedPreferences("WX_INFO", Context.MODE_PRIVATE);
		wx_token=sharedPreferences.getString("token", "");
		//获取sharedPreferences里面的信息,普通登陆
		sharedPreferences = getSharedPreferences("Normal_Info",Context.MODE_PRIVATE);
		nor_token=sharedPreferences.getString("NORMAL_Token", "");
		if(!(""==wx_token)){
			token=wx_token;
		}else{
			token=nor_token;
		}
		if(TextUtils.isEmpty(token)){
			
		}
		arrowWebView=(WebView) findViewById(R.id.arrow_Web);
		/*back=(ImageButton) findViewById(R.id.back);
		back.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
			finish();
				
			}
		});
		title=(TextView) findViewById(R.id.title);*/
		arrowDetailsWebActivity =this;
		Intent intent=getIntent();
		all_order_url = intent.getStringExtra("all_order");
		pay_arrow_url = intent.getStringExtra("pay_arrow");
		accept_arrow_url = intent.getStringExtra("accept_arrow");
		arrow_evaluate_url = intent.getStringExtra("arrow_evaluate");
		back_arrow_url = intent.getStringExtra("back_arrow");
		repair_url = intent.getStringExtra("repair");
		address_management_url=intent.getStringExtra("address_management");
		showcenter_url=intent.getStringExtra("showcenter");
		myshow_url=intent.getStringExtra("myshow");
		WebSettings webSettings = arrowWebView.getSettings();  
	    //设置WebView属性，能够执行Javascript脚本    
	    webSettings.setJavaScriptEnabled(true);    
	    //设置可以访问文件  
	    webSettings.setAllowFileAccess(true);  
	  //webview自适应屏幕
	    webSettings.setUseWideViewPort(true); 
	    webSettings.setLoadWithOverviewMode(true); 
	    arrowWebView.addJavascriptInterface(new JavaScriptObject(ArrowDetailsWebActivity.this),"android");       
	    if(!(null==all_order_url)){
	    	setActionBarTitle("全部订单");
	    	url=all_order_url;
	    	Log.e("url",url);
	    	arrowWebView.loadUrl(url+"&token="+token+"&appType=2"); 
	    }else if(!(null==pay_arrow_url)){
	    	setActionBarTitle("待付订单");
	    	url=pay_arrow_url;
	    	arrowWebView.loadUrl(url+"&token="+token+"&appType=2");
	    }else if(!(null==accept_arrow_url)){
	    	setActionBarTitle("代收订单");
	    	url=accept_arrow_url;
	    	arrowWebView.loadUrl(url+"&token="+token+"&appType=2");
	    }else if(!(null==arrow_evaluate_url)){
	    	setActionBarTitle("订单评价");
	    	url=arrow_evaluate_url;
	    	arrowWebView.loadUrl(url+"&token="+token+"&appType=2");
	    }else if(!(null==back_arrow_url)){
	    	setActionBarTitle("订单溯源");
	    	url=back_arrow_url;
	    	arrowWebView.loadUrl(url+"&token="+token+"&appType=2");
	    }else if(!TextUtils.isEmpty(repair_url)){
	    	setActionBarTitle("返修/退换");
	    	url=repair_url;
	    	arrowWebView.loadUrl(url+"&token="+token+"&appType=2");   
	    }else if(!(null==address_management_url)){
	    	url=address_management_url;
	    	arrowWebView.loadUrl(url); 
	    }else if(!(null==showcenter_url)){	   
	    	setActionBarTitle("秀场动态");
	    	url=showcenter_url;
	    	arrowWebView.loadUrl(url+"&token="+token+"&appType=2"); 
	    }else{	    	
	    	setActionBarTitle("我的秀场");
	    	url=myshow_url;
	    	arrowWebView.loadUrl(url+"&token="+token+"&appType=2"); 
	    }
	    Log.e("arrowweb-----------------------", url+"&token="+token+"&appType=2");
	    //设置Web视图  
	   
	    arrowWebView.setWebViewClient(new WebViewClient(){
	        @Override
	        public boolean shouldOverrideUrlLoading(WebView view, String url) {
	            view.loadUrl(url);
	            return true;
	        }
	       
	        @Override
	        public void onPageStarted(WebView view, String url, Bitmap favicon) {
	        	
	        	super.onPageStarted(view, url, favicon);
	     
	        
	    	
	        }
	        
	        @Override
			public void onPageFinished(WebView view, String url) {
				
				super.onPageFinished(view, url);
				

			}
	    });
	 
	    arrowWebView.setWebChromeClient(new MyWebChromeClient());
	}
	
	public class JavaScriptObject {
		 Context mContext;

		public JavaScriptObject(Context mContext) {
			super();
			this.mContext = mContext;
		}
		 
		@JavascriptInterface
		 public void loadHomePage() {
		
			Intent intent =new Intent(ArrowDetailsWebActivity.this,MainActivity.class);
			MainActivity.MAIN_FRAM_TAG =MainActivity.TO_FRAG_HOME_TAG;
			startActivity(intent);
			finish();
		} 
		@JavascriptInterface
		 public void goToShoppingCart() {
			Intent intent =new Intent(ArrowDetailsWebActivity.this,MainActivity.class);
			MainActivity.MAIN_FRAM_TAG =MainActivity.TO_FRAG_SHOPCART_TAG;
			startActivity(intent);
			finish();
			
		} 
		
		@JavascriptInterface
		public void appLoginFunc(){
			Intent intent =new Intent (ArrowDetailsWebActivity.this,LoginActivity.class);
			startActivity(intent);
		}
		@JavascriptInterface
		 public void appWeixinPay(String a) {
		
			sharedPreferences =getSharedPreferences("PAY", Context.MODE_PRIVATE);
			sharedPreferences.edit().clear();
			sharedPreferences.edit().putString("PAYINFO", a).commit();
			JSONObject json;
			try {
				json = new JSONObject(a);
				JSONObject payData = json.getJSONObject("data");
				Log.e("json",json.toString());
				
				if(json == null)
					return;
				
				
				PayReq req = new PayReq();
				
				req.appId =payData.getString("appId");
				Log.e("appId",req.appId);
				req.partnerId = payData.getString("partnerid");
				Log.e("partnerId",req.partnerId);
				req.prepayId=  payData.getString("prepayid");
				Log.e("prepayId",req.prepayId);
				req.packageValue = payData.getString("package_");
				Log.e("packageValue",req.packageValue);
				req.nonceStr=  payData.getString("noncestr");
				Log.e("nonceStr",req.nonceStr);
				req.timeStamp= payData.getString("timeStamp");
				Log.e("timeStamp",req.timeStamp);
				 req.sign= payData.getString("sign");
				 Log.e("sign",req.sign);
				
				List<NameValuePair> signParams = new LinkedList<NameValuePair>();
	            signParams.add(new BasicNameValuePair("appid", req.appId));
				signParams.add(new BasicNameValuePair("noncestr", req.nonceStr));
				signParams.add(new BasicNameValuePair("package", req.packageValue));
				signParams.add(new BasicNameValuePair("partnerid", req.partnerId));
				signParams.add(new BasicNameValuePair("prepayid", req.prepayId));
				signParams.add(new BasicNameValuePair("timestamp", req.timeStamp));
				
				req.sign = genAppSign(signParams);
				
				api.sendReq(req);
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			
			}		
		
		}
		
		// 二次签名
		private String genAppSign(List<NameValuePair> params) {
			StringBuilder sb = new StringBuilder();

			for (int i = 0; i < params.size(); i++) {
				sb.append(params.get(i).getName());
				sb.append('=');
				sb.append(params.get(i).getValue());
				sb.append('&');
			}
			sb.append("key=");
			sb.append(Constants.API_KEY);

			String appSign = MD5.getMessageDigest(sb.toString().getBytes()).toUpperCase();
		
			return appSign;
		}
	}
	
	 @SuppressLint("NewApi")
	protected void onActivityResult(int requestCode, int resultCode, Intent intent){
		 if (requestCode == FILECHOOSER_RESULTCODE) {
				if (null == mUploadMessage)
					return;
				Uri result = intent == null || resultCode != RESULT_OK ? null
						: intent.getData();
				mUploadMessage.onReceiveValue(result);
				mUploadMessage = null;
			}else if (requestCode == REQUEST_SELECT_FILE) {
		            if (uploadMessage == null) return;
		            uploadMessage.onReceiveValue(WebChromeClient.FileChooserParams.parseResult(resultCode,  intent));
		            uploadMessage = null;
		        }
	    }
	 
	 public class MyWebChromeClient extends WebChromeClient {
	        // reference to activity instance. May be unnecessary if your web chrome client is member class.
//	        private MainActivity myActivity;

		 public void onProgressChanged(WebView view, int progress) {

			}
		 //5.0
	        @SuppressLint("NewApi")
			public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, FileChooserParams fileChooserParams) {



	            // make sure there is no existing message
	            if (arrowDetailsWebActivity .uploadMessage != null) {
	                arrowDetailsWebActivity .uploadMessage.onReceiveValue(null);
	                arrowDetailsWebActivity .uploadMessage = null;
	            }

	            arrowDetailsWebActivity .uploadMessage = filePathCallback;

	            Intent intent = fileChooserParams.createIntent();
	            try {
	                arrowDetailsWebActivity .startActivityForResult(intent, arrowDetailsWebActivity.REQUEST_SELECT_FILE);
	            } catch (Exception e) {
	                arrowDetailsWebActivity .uploadMessage = null;
	                Toast.makeText(arrowDetailsWebActivity , "Cannot open file chooser", Toast.LENGTH_LONG).show();
	                return false;
	            }

	            return true;
	        }
	        
	     // For 3.0+ Devices (Start)
	     			// onActivityResult attached before constructor
	     			protected void openFileChooser(ValueCallback uploadMsg,
	     					String acceptType) {
	     				mUploadMessage = uploadMsg;
	     				Intent i = new Intent(Intent.ACTION_GET_CONTENT);
	     				i.addCategory(Intent.CATEGORY_OPENABLE);
	     				i.setType("image/*");
	     				startActivityForResult(Intent.createChooser(i, "File Browser"),
	     						FILECHOOSER_RESULTCODE);
	     			}
	     			
	     		// For Android 4.1 only
	    			protected void openFileChooser(ValueCallback<Uri> uploadMsg,
	    					String acceptType, String capture) {
	    				mUploadMessage = uploadMsg;
	    				Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
	    				intent.addCategory(Intent.CATEGORY_OPENABLE);
	    				intent.setType("image/*");
	    				startActivityForResult(
	    						Intent.createChooser(intent, "File Browser"),
	    						FILECHOOSER_RESULTCODE);
	    			}

	    			protected void openFileChooser(ValueCallback<Uri> uploadMsg) {
	    				mUploadMessage = uploadMsg;
	    				Intent i = new Intent(Intent.ACTION_GET_CONTENT);
	    				i.addCategory(Intent.CATEGORY_OPENABLE);
	    				i.setType("image/*");
	    				startActivityForResult(Intent.createChooser(i, "File Chooser"),
	    						FILECHOOSER_RESULTCODE);
	    			}
	    }
	 
	 private Intent createDefaultOpenableIntent() {  
      // Create and return a chooser with the default OPENABLE  
      // actions including the camera, camcorder and sound  
      // recorder where available.  
      Intent i = new Intent(Intent.ACTION_GET_CONTENT);  
      i.addCategory(Intent.CATEGORY_OPENABLE);  
      i.setType("*/*");  

      Intent chooser = createChooserIntent(createCameraIntent(),  
              createCamcorderIntent(), createSoundRecorderIntent());  
      chooser.putExtra(Intent.EXTRA_INTENT, i);  
      return chooser;  
  }  

  private Intent createChooserIntent(Intent... intents) {  
      Intent chooser = new Intent(Intent.ACTION_CHOOSER);  
      chooser.putExtra(Intent.EXTRA_INITIAL_INTENTS, intents);  
      chooser.putExtra(Intent.EXTRA_TITLE, "File Chooser");  
      return chooser;  
  }  

  private Intent createCameraIntent() {  
      Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);  

      File externalDataDir = Environment  
              .getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);  
      System.out.println("externalDataDir:" + externalDataDir);  
      File cameraDataDir = new File(externalDataDir.getAbsolutePath()  
              + File.separator + "browser-photo");  
      cameraDataDir.mkdirs();  
      mCameraFilePath = cameraDataDir.getAbsolutePath() + File.separator  
              + System.currentTimeMillis() + ".jpg";  
      System.out.println("mcamerafilepath:" + mCameraFilePath);  
      cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT,  
              Uri.fromFile(new File(mCameraFilePath)));  

      return cameraIntent;  
  }  

  private Intent createCamcorderIntent() {  
      return new Intent(MediaStore.ACTION_VIDEO_CAPTURE);  
  }  

  private Intent createSoundRecorderIntent() {  
      return new Intent(MediaStore.Audio.Media.RECORD_SOUND_ACTION);  
  }  
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if ((keyCode == KeyEvent.KEYCODE_BACK) &&  arrowWebView.canGoBack()) {
			arrowWebView.goBack();
			 return true;
			}else{
				finish();
			}
			return super.onKeyDown(keyCode, event);
		}
}
